package indigo.ueditor.handler;

import java.io.File;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.Set;

import javax.servlet.http.HttpServletRequest;

import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import com.google.common.io.Files;
import com.google.common.primitives.Ints;

import indigo.ueditor.UEditorFileManager;
import indigo.ueditor.UEditorHandler;
import indigo.ueditor.UEditorState;

public class ResourceListHandler implements UEditorHandler {
	private final String name;
	private final UEditorFileManager fileManager;
	private final int listSize;
	private final String basePath;
	private final Set<String> supportedSuffixes;

	public ResourceListHandler(String name, UEditorFileManager fileManager,
			int listSize, String basePath, Set<String> supportedSuffixes) {
		this.name = name;
		this.fileManager = fileManager;
		this.listSize = listSize;
		this.basePath = basePath;
		this.supportedSuffixes = supportedSuffixes;
	}

	@Override
	public String getName() {
		return name;
	}

	@Override
	public Object handle(HttpServletRequest request) {
		String start = request.getParameter("start");
		int offset = start != null ? Optional.ofNullable(Ints.tryParse(start)).orElse(0) : 0;

		List<File> list = fileManager.listFiles(basePath, file -> {
			String fileExtension = Files.getFileExtension(file.getName());
			String fileSuffix = fileExtension.isEmpty() ? "" : "." + fileExtension;
			return supportedSuffixes.contains(fileSuffix);
		});

		List<Map<String, Object>> results = Lists.newArrayList();
		for (int i = offset; i < offset + listSize && i < list.size(); ++i) {
			results.add(Collections.singletonMap("url", fileManager.getFileUrl(list.get(i))));
		}

		Map<String, Object> result = Maps.newHashMap();
		result.put("state", UEditorState.SUCCESS.getMessage());
		result.put("start", start);
		result.put("total", list.size());
		result.put("list", results);
		return Collections.unmodifiableMap(result);
	}
}
